1540B - Tree Array - CodeForces Solution


brute force combinatorics dp graphs math probabilities trees *2300

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define int long long

const int maxn = 209,modd = 1e9 + 7;
using namespace std;

int n,dep[maxn],fa[maxn][25],f[maxn][maxn];

vector<int> g[maxn];

int qp(int a,int b){
  int res = 1;
  while(b){
    if(b&1)res = (res*a)%modd;
    a = (a*a)%modd;
    b>>=1;
  }
  return res % modd;
}

void dfs(int u,int f){
  dep[u] = dep[f] + 1;
  fa[u][0] = f;
  for(int i = 1;i<=20;++i)
    fa[u][i] = fa[fa[u][i-1]][i-1];

  for(int v : g[u]){
    if(v!=f){
      dfs(v,u);
    }
  }
}

int lca(int x,int y){
  if(dep[x]>dep[y])swap(x,y);
  for(int i = 20;i>=0;i--)if(dep[fa[y][i]]>=dep[x])y = fa[y][i];
  if(x==y)return x;
  for(int i = 20;i>=0;i--)if(fa[x][i]!=fa[y][i])x = fa[x][i],y = fa[y][i];
  return fa[x][0];
}

signed main(){
  scanf("%lld",&n);
  for(int i = 1,u,v;i<n;++i){
    scanf("%lld%lld",&u,&v);
    g[u].push_back(v),g[v].push_back(u);
  }

  int inv2 = qp(2,modd-2);
  for(int i = 1;i<=n;++i)f[0][i] = 1;
  for(int i = 1;i<=n;++i){
    for(int j = 1;j<=n;++j){
      f[i][j] = (f[i-1][j] + f[i][j-1])*inv2%modd;
    }
  }

  int ans = 0;
  for(int i = 1;i<=n;++i){
    dfs(i,0);
    for(int j = 1;j<=n;++j){
      for(int k = 1;k<j;++k){
	int _lca = lca(j,k);
	ans = (ans + f[dep[j] - dep[_lca]][dep[k] - dep[_lca]])%modd;
      }
    }
  }

  printf("%lld",ans*qp(n,modd-2)%modd);
}


Comments

Submit
0 Comments
More Questions

50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence
42. Trapping Rain Water
32. Longest Valid Parentheses
Cutting a material
Bubble Sort
Number of triangles
AND path in a binary tree
Factorial equations
Removal of vertices
Happy segments
Cyclic shifts